const dataBase = {
  catename: '',
  page: '1',
  limit: '10'
}
async function render() {
  const { data: { data: res } } = await axios.get('/ydd_cate/list', { params: dataBase })
  console.log(res)
  console.log(res.data)
  const htmlStr = res.data.map((ele, index) => {
    const { sort_num, id, catename, icon, default_data } = ele
    return `
        <tr>
          <td style="width: 30px;">${index + 1}</td>
          <td>${id}</td>
          <td>${catename}</td>
          <td>${icon}<i class="fa ${icon}" ></i></td>
          <td>${sort_num}</td>
          <td>
            <button type="button" class="layui-btn layui-btn-sm layui-btn-radius layui-btn-normal eidtBtn" data-id="${id}" data-index="${default_data}" ><i
                class="layui-icon">&#xe642;</i></button>
            <button type="button" class="layui-btn layui-btn-sm layui-btn-radius layui-btn-danger delBtn" data-id="${id}"><i
                class="layui-icon">&#xe640;</i></button>
          </td>
        </tr>
    `
  }).join('')
  $('.tbody').html(htmlStr)
  renderPage(res.count)
}
render()
// ===========分页
let laypage = layui.laypage;
function renderPage(count) {
  //执行一个laypage实例
  laypage.render({
    elem: 'page-box', //注意，这里的 test1 是 ID，不用加 # 号
    count,//数据总数，从服务端得到
    limit: dataBase.limit,
    limits: [10, 20, 50, 80, 100],
    curr: dataBase.page,
    layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'],
    jump: function (obj, first) {
      //obj包含了当前分页的所有参数，比如：
      // console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
      // console.log(obj.limit); //得到每页显示的条数
      // console.log(first)
      dataBase.page = obj.curr
      dataBase.limit = obj.limit
      //首次不执行
      if (!first) {
        //do something
        // console.log('a');
        render()
      }
    }
  });
}
//  =======================删除功能
let layer = layui.layer
$('.tbody').on('click', '.delBtn', function () {
  // alert(1)
  const id = $(this).attr('data-id')
  layer.confirm('确定要删除吗?', { icon: 3, title: '提示' }, async function (index) {
    //do something
    await axios.get('/ydd_cate/del', { params: { id } })
    layer.msg('删除成功')
    render()
    layer.close(index);
  });
})
// 模态框
let index
$('.addBtn').on('click', function () {
  $('.text-1').html('1')
  console.log($('.text-1').html())
  index = layer.open({
    title: '添加分类',
    content: $("#editForm"),
    type: 1,
    area: ['700px', '400px'],
  })
})

$('body').on('click', '#Add', function () {
  // alert(1)
  $('#prev').prop('disabled', false)
  let i = $('.intVal').val()
  i++
  $('.intVal').val(i)
  // $('.intVal').html(i)


  // console.log(val)
})
$('body').on('click', '#prev', function () {
  // alert(1)
  let i = $('.intVal').val()
  if (i == 1) {
    $(this).prop('disabled', true)
    return
  }
  i--
  $('.intVal').val(i)
  // $('.intVal').html(i)
  // console.log(val)
})

// ==========公共
let flag = true
$('#btn1').click(function () {
  let r = 0
  if (flag) {
    $('#header').hide()
    flag = false
    r += 180;
    $('#btn1').css('transform',`rotate(${r}deg)`);
  } else {
    $('#header').show()
    flag = true
    $('#btn1').css('transform', `rotate(0deg)`);
  }
})
// =============编辑
const form = layui.form
let default_data
let id
$('body').on('click', '.eidtBtn', async function () {
  id = $(this).attr('data-id')
  $('.text-1').html('2')
  default_data = $(this).attr('data-index')
  // console.log($('.layui-layer-title').val())
  console.log($('.text-1').html())
  index = layer.open({
    title: '修改分类',
    content: $("#editForm"),
    type: 1,
    area: ['700px', '400px'],
  })
  // /ydd_cate/rowInfo
  const { data: { data } } = await axios.get('/ydd_cate/rowInfo', { params: { id } })
  // console.log(data)
  form.val("formTest", data)
  $('.intVal').attr('value', `10`)
})

// =======添加
$('.btnClose').on('click', async function (e) {
  e.preventDefault()
  const catename = $('[name=catename]').val()
  const icon = $('[name=icon]').val()
  const sort_num = +$('[name=sort_num]').val()
  if ($('.text-1').html() == 2) {
    const res = await axios.post('/ydd_cate/update', { catename, icon, sort_num, default_data ,id})
    // console.log(res)
    layer.close(index)
    layer.msg('修改成功')
    render()
    $('#editForm')[0].reset()
    $('.intVal').val('10')
  } else {
    const res = await axios.post('/ydd_cate/add', { catename, icon, sort_num, })
    // console.log(res)
    layer.close(index)
    layer.msg('添加成功')
    render()
    $('#editForm')[0].reset()
    $('.intVal').val('10')
  }
})
//  ==============搜索  
 $('.searchBtn').on('click',function(){
  const searchName = $('[name=searchName]').val()
  dataBase.catename = searchName
  render()
  dataBase.catename = ''
 })
$('.serchForm').on('submit',function(e){
  e.preventDefault()
})
$('.reset').click(function(){
  render()
})
// ==============导出
$('.outBtn').click(function () {

  var table = document.getElementById("tabInfo")
  var data = []
  for (var i = 0, row; row = table.rows[i]; i++) {
    var rowData = []
    for (var j = 0, col; col = row.cells[j]; j++) {
      rowData.push(col.innerText)
    }
    data.push(rowData)
  }
  // 创建工作簿
  var workbook = XLSX.utils.book_new()

  // 创建工作表
  var worksheet = XLSX.utils.aoa_to_sheet(data)

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1")

  // 导出工作簿为 Excel 文件
  XLSX.writeFile(workbook, "数据.xlsx")
})